package me.fung.rem.app.content

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.VectorConverter
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.input.pointer.PointerEventType.Companion.Exit
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import me.fung.rem.app.GlobalState
import me.fung.rem.app.navigation
import me.fung.rem.app.settings.PAGE_SETTINGS
import me.fung.rem.app.settings.PAGE_TAG_VIEW

@OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterialApi::class)
@Composable
fun ContentView.buttonSetting(modifier: Modifier) {
    val state = remember { GlobalState }
    var expanded by remember { mutableStateOf(false) }
    val size = remember {
        Animatable(0.dp, Dp.Companion.VectorConverter)
    }
    LaunchedEffect(expanded) {
        size.animateTo(if (expanded) Dp.Unspecified else 0.dp)
    }
    Box(modifier = modifier) {
        TextButton(
            onClick = { expanded = !expanded },
            modifier = Modifier.align(Alignment.TopEnd),
        ) {
            Icon(Icons.Default.Settings, contentDescription = null)
        }

        CompositionLocalProvider(LocalMinimumInteractiveComponentEnforcement provides false) {
            Column(
                modifier = Modifier.height(size.value).onPointerEvent(Exit) {
                    expanded = !expanded
                }.shadow(1.dp, RoundedCornerShape(5.dp)).width(IntrinsicSize.Max),
            ) {
                settingButton(buttonText = "导出", onClick = { p.write() })
                settingButton(buttonText = "导入", onClick = { p.read() })
                settingButton(buttonText = "设置>>", onClick = { navigation.goto(PAGE_SETTINGS) })
                settingButton(buttonText = "管理标签>>", onClick = { navigation.goto(PAGE_TAG_VIEW) })
                settingButton(buttonText = "退出登录", onClick = { state.authorized = false })
            }
        }
    }
}

@Composable
private fun settingButton(buttonText: String, onClick: () -> Unit) {
    Button(
        shape = RoundedCornerShape(0.dp),
        modifier = Modifier.fillMaxWidth(),
        onClick = onClick
    ) {
        Text(buttonText)
    }
}